<?php
namespace BoxAdmin\Controller;

use Think\Controller;

class SystemController extends CommonController
{
    public function _initialize()
    {
        parent::_initialize();

        $this->payment = BoxModel('SystemPayment');
        $this->give = BoxModel('system_logistics');
        $this->id = I('id', '', 'intval');
        $this->kw = I('get.kw');
        $this->store_id = I('store_id', 1);

    }

    /**
     * [UpPaySort 更新排序]
     */
    public function UpSort()
    {
        $model = I("model");
        $value = I("value");
        $key = I("key");
        $key_value = I('key_value');
        if (M($model)->where(array($key => $key_value))->setField('sort_order', $value)) {
            echo 1;
        } else {
            echo 0;
        }


    }

    /**
     * 系统管理首页
     */
    public function index()
    {
        $this->memuNav = "index";
        $store = BoxModel("SystemStore");
        $where = 'isOpen=1';
        if (!empty($this->kw)) {
            $where .= ' and (store_name like "%' . $this->kw . '%" or photo like "%' . $this->kw . '%" or domain like "%' . $this->kw . '%")';
        }
        $order = 'store_id desc';
        $data = $store->get($where, 10, $order);
        $this->list = $data['list'];
        $this->show_page($data['pager']);
        $this->display();
    }

    /**
     * [add 添加或修改商户页]
     */
    public function storeAdd()
    {
        $this->store_id = I('store_id', "", "intval");
        if (!empty($this->store_id)) {
            $this->data = BoxModel("SystemStore")->load($this->store_id);
            $this->user_data = BoxModel("system_store_user")->where(array('store_id' => $this->store_id, 'pid' => 0))->find();
        }
        $this->display();
    }


    /**
     * [wechatInsert 添加或修改商户方法]
     *
     */
    public function storeInsert()
    {
        $model = D('SystemStore');
        if (IS_POST) {
            $arr = $model->create();
            $this->store_id = I('store_id');
            if ($user_name = I('user_name')) {
                $row = array(
                    'pid' => 0,
                    'user_name' => I('user_name'),
                    //'password'=>I('password'),
                );
            }
            if ($password = I('password')) {
                $row['password'] = md5($password);
            }
            if ($this->store_id) {
                $model->where(array('store_id' => $this->store_id))->save($arr);
                BoxModel("system_store_user")->where(array('store_id' => $this->store_id, 'pid' => 0))->save($row);
            } else {
                $r = BoxModel('system_store_user')->where(array('user_name' => I('user_name')))->find();
                if ($r) {
                    $this->jump("用户名已占用");
                }
                $this->store_id = $model->add($arr);
                $row['store_id'] = $this->store_id;
                $row['pasttime'] = time();
                BoxModel('system_store_user')->add($row);
            }
            $this->jump("操作成功");

        }
    }

    /**
     * 检测用户名是否存在
     */
    public function checkdomain()
    {
        $store_id = I('store_id');
        $find2 = BoxModel("system_store")->load($store_id);
        $find = BoxModel("system_store")->ByField("domain", I('domain'));
        if ($find && $find2['domain'] != I('domain')) {
            echo json_encode(array(
                'valid' => false,
            ));
        } else {
            echo json_encode(array(
                'valid' => true,
            ));
        }
    }

    /**
     * [wechatDel 删除商户帐号]
     * @return [type] [description]
     */
    public function storeDel()
    {

        $del = BoxModel("SystemStore")->where(array('store_id' => I('id')))->save(array('isOpen' => 2));
        $del = BoxModel("system_store_user")->where(array('store_id' => I('id')))->save(array('status' => 2));
        if ($del) {
            $this->redirect('index');
        } else {
            $this->jump('删除失败！');
        }
    }


    /**
     * [upSsort 更新轮播图排序]
     * @return [type] [description]
     */
    public function upSsort()
    {
        foreach ($_POST as $id => $sort) {
            $this->slide->where(array('id' => $id))->setField('sort', $sort);
        }

        $this->jump("成功");
    }

    /**
     * [payment 支付方式列表页]
     * @return [type] [description]
     */
    public function payment()
    {
        $this->memuNav = 'payment';
        $code = C('payment');
        foreach ($code as $k => $v) {
            $data = $this->payment->where(array('store_id' => $this->store_id,
                'payment_code' => $k))->find();
            $code[$k]['enabled'] = $data['enabled'];
        }
        $count = count($code);
        $this->setPager('', 2000, '', $count);
        $this->code = $code;
        $this->display();
    }

    /**
     * 配置支付方式页
     */
    public function paymentAdd()
    {
        $this->memuNav = 'payment';
        $code = I('get.code');
        $name = I('get.name');
        $this->code = $code;
        $this->name = $name;

        $configData = C('payment.' . $code);
        $this->title = $configData['title'];
        $this->type = $configData['type'];
        unset($configData['type']);
        unset($configData['title']);

        $this->configData = $configData;
        $this->data = $this->payment->where(array('payment_code' => $code, 'store_id' => $this->store_id))->find();
								//dump($this->data);
        $this->configValue = json_decode($this->data['config'], true);
        $this->display();
    }

    /**
     * 添加 修改支付方式
     */
    public function paymentInsert()
    {
        $data = array(
            'payment_code' => I('post.code'),
            'payment_name' => I('post.payment_name'),
            'payment_desc' => I('post.payment_desc'),
            'store_id' => $this->store_id,
            'config' => json_encode(I('config')),
            'enabled' => 1,
            'type' => I('type'),
        );

        $info = $this->_upload();
        if (is_array($info)) {
            $data['img'] = $info['img']['savepath'] . $info['img']['savename'];
        }

        $find = $this->payment->where(array('store_id' => $this->store_id,
            'payment_code' => $data['payment_code']))->find();
        if ($find) {
            $this->payment->where(array('payment_code' => $data['payment_code'], 'store_id' => $this->store_id))->save($data);
            $this->jump("修改成功");
            // D('Log')->addLogs(session('user_name'), '修改支付方式');
        } else {
            $this->payment->add($data);
            $this->jump("添加成功", U('payment'));
            //  D('Log')->addLogs(session('user_name'), '添加支付方式');
        }

    }

    /**
     * [enabled 开启  关闭支付方式]
     * @return [type] [description]
     */
    public function enabled()
    {
        $code = I('get.code', '', 'htmlspecialchars');
        $close = I('get.close', '', 'intval');
        switch ($close) {
            case 0:
                $this->payment->where(array('payment_code' => $code))->setField('enabled', 0);
                //  D('Log')->addLogs(session('user_name'),'关闭支付方式');
                $this->redirect('payment');
                break;
            case 1:
                $this->payment->where(array('payment_code' => $code))->setField('enabled', 1);
                //  D('Log')->addLogs(session('user_name'),'开启支付方式');
                $this->redirect('payment');
                break;
        }
    }

    /**
     * 删除支付方式
     */
    public function paymentDel()
    {
        if ($this->payment->delPay($this->id)) {
            //  D('Log')->addLogs(session('user_name'),'删除支付方式');
            $this->redirect('payment');
        }
    }

    /**
     * 配送方式首页
     */
    public function give()
    {
        $this->memuNav = 'give';
        $where = "store_id='$this->store_id'";
        if (!empty($this->kw)) {
            $where = 'name like "%' . $this->kw . '%"';
        }
        $order = 'id desc';
        $data = $this->give->get($where, 10, $order);
        $this->list = $data['list'];
        $this->show_page($data['pager']);
        $this->display();
    }

    /**
     * 添加 修改配送方式页
     */
    public function giveAdd()
    {
        $this->memuNav = 'give';
        if ($this->id) {
            $this->data = $this->give->where('id=' . $this->id)->find();
        }

        $this->display();
    }

    /**
     * [giveInsert 添加 修改配送方式行为]
     * @return [type] [description]
     */
    public function giveInsert()
    {
        $data['name'] = I('post.name');
        $data['fee'] = I('post.fee');
        $data['tel'] = I('post.tel');
        $data['code'] = I('post.code');
        $data['website'] = urlSet(I('post.website'));
        $data['store_id'] = $this->store_id;
        if (empty($this->id)) {
            if ($this->give->add($data)) {
                $this->redirect('give');
            } else {
                $this->error('添加失败');
            }
        } else {
            $data['status'] = I('post.status', 0, 'intval');
            $data['name'] = I('post.name');
            $data['fee'] = I('post.fee');
            $data['website'] = urlSet(I('post.website'));
            $this->give->where(array('id' => $this->id))->save($data);
            $this->jump("修改成功");
        }
    }

    /**
     * [giveDel 删除配送方式]
     * @return [type] [description]
     */
    public function giveDel()
    {
        if ($this->give->where('id=' . $this->id)->delete()) {
            $this->redirect('give');
        }
    }


    /**
     * 邮件设置
     * Write 写入文件函数
     */
    public function emailSet()
    {
        $this->memuNav = 'emailSet';
        $data = BoxModel('system_store')->where(array('store_id' => $this->store_id))->find();
        $this->data = json_decode($data['email_setting'], true);
        $this->display();

    }

    /**
     * 接收表单提交信息
     */
    public function setEmail()
    {
        if (IS_POST) {
            $row = array(
                'smtp' => I('smtp'),
                'port' => I('port'),
                'url' => I('url'),
                'username' => I('username'),
                'password' => I('password'),
                'ceshiurl' => I('ceshiurl'),
            );
            $data['email_setting'] = json_encode($row);
            BoxModel('system_store')->where(array('store_id' => $this->store_id))->save($data);
            $this->redirect('emailSet');
        }
    }


    /******测试发邮件*******/
    public function testEmail()
    {
        $to = I("to");
        $EmailObj = new \Common\Org\spEmail();
        $EmailObj->sendmail($to, "来自pointshop测试，邮件", "你好，邮件测试成功", "HTML");
    }

    /**
     *
     * 短信设置
     */
    public function smsSet()
    {
        $this->memuNav = 'smsSet';
        $data = BoxModel('system_store')->load($this->store_id);
        $this->data = json_decode($data['sms_setting'], true);
        $this->display();
    }

    public function setSMS()
    {
        if (IS_POST) {
            $data = array(
                'keyword' => I('keyword'),
                'password' => I('password'),
            );
            $row['sms_setting'] = json_encode($data);
            //dump(BoxModel('system_store'));exit();
            $r = BoxModel('system_store')->where(array('store_id' => $this->store_id))->save($row);
            $this->jump('保存成功');
        }
    }


    public function logo_up()
    {

        list($width, $height) = getimagesize($_FILES['pic']["tmp_name"]);
        $imgtype = $_FILES['pic']['type'];
        /*if($width != 120 ||  $height != 40){
            exit(json_encode(array('error'=>1,'msg'=>'图片宽度必须为120px,高度为40px')));
        }
        if($imgtype != 'image/png'){
            exit(json_encode(array('error'=>2,'msg'=>'只能上传PNG格式图片')));
            
        }*/
        $info = $this->_upload("/logo/");
        if ($info != false) {
            $logo = $info['pic']['savepath'] . $info['pic']['savename'];
            BoxModel('system_store')->where(array('store_id' => $this->store_id))->setField('logo', $logo);
            exit(json_encode(array('error' => 0, 'msg' => ImgDomain . $logo)));
        }
    }

    /**********运费设置**/
    public function freight()
    {
        $this->memuNav = 'freight';
        if (IS_POST) {
            $config = I('config');
            $freight_config = json_encode($config);
            $r = D('SystemMember')->where(array('store_id' => 1))->save(array('freight_config' => $freight_config));
            //   dump(D('SystemMember'));
        }
        $data = BoxModel('SystemMember')->load(1);
        $this->feeconfig = json_decode($data['freight_config'], true);
        // dump($this->feeconfig);
        $this->area = BoxModel("SystemArea")->childs(0);
        $this->display();
    }

    public function city_area()
    {
        $pid = I('pid');
        $area = BoxModel("SystemArea")->where("(area_type=2 and parent_id='$pid' ) or (area_id='$pid')")->order("area_id")->select();
        echo json_encode($area);
    }

    public function dict()
    {
        $where = "1";
        if ($this->kw = I('kw')) {
            $where .= " and (name like '%$this->kw%' or remark like '%$this->kw%')";
        }
        $count = BoxModel("system_dict")->where($where)->count();
        $pager = setPager($count, 10);
        $this->data = BoxModel("system_dict")->where($where)->order("addtime desc")->limit($pager['limit'])->select();
        $this->show_page($pager);
        $this->display();
    }

    public function dict_add()
    {
        $name = I('name');
								$this->showName=I('showName');
        $data = BoxModel("system_dict")->find($name);
        $data['value'] = json_decode($data['value'], true);
								$this->type="string";
        if (is_array($data['value'])) {
            $data['value'] = arrayeval($data['value']);
												$this->type="array";
        }
        $this->data = $data;
        if (IS_POST) {
            $name = I('name');
            $value_str = str_replace("Array", "array", stripslashes(htmlspecialchars_decode($_POST['value'])));
												if(strpos($value_str,"array")!==0){
												  $value_str="'".$value_str."'";
												}
            eval("\$value = " . $value_str . "; ");
            dict($name, $value, I('remark'));
            $this->jump("保存成功", "/BoxAdmin/".U('dict_add', array('name' => $name)));
        }
        $this->display();
    }

    public function dict_del()
    {
        $name = I('name');
        BoxModel("system_dict")->where(array('name' => $name))->delete();
        $this->jump();
    }

    public function smsTest()
    {
        $tel = I('tel');
        $r = sms($tel, "测试验证码：34355");
        dump($r);
    }


    /*****积分模板****/
    public function log_template()
    {
        $this->log_type = dict("log_type");
        $id = I('id');
        $model = BoxModel("system_log_template");
        $where = 1;
        if ($kw = I('kw')) {
            $where .= " and (title like '%$kw%' or type like '%$kw%' or event like '%$kw%'  or content like '%$kw%')";
        }
        //$model->where("1")->save(array('public'=>1));
        $data = $model->get("", 50, "id");
        $this->data = $data['list'];
        $this->show_page($data['pager']);
        $this->display();
    }

    public function add_log_template()
    {
        $this->log_type = dict("log_type");
        $id = I('id');
        $model = BoxModel("system_log_template");
        if (IS_POST) {
            $row = $model->create();
            if ($id) {
                $model->save($row);
            } else {
                $row['add_date'] = date("Y-m-d H:i:s");
                $id = $model->add($row);
            }
            $this->jump("", U('add_log_template', array('id' => $id)));
        }
        if ($id) {
            $this->data = $model->where(array('id' => $id))->find();
        }
        $this->display();
    }

    public function del_log_template()
    {
        $id = I('id');
        BoxModel("system_log_template")->where(array('id' => $id))->delete();
        $this->jump("删除成功");
    }


}

?>